package com.wind.trademark.task.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.wind.trademark.base.model.BsCategory;
import com.wind.trademark.client.model.CtCompany;
import com.wind.trademark.common.dao.BaseDao;
import com.wind.trademark.common.exception.TmException;
import com.wind.trademark.common.vo.ComboBean;
import com.wind.trademark.common.vo.PageBean;
import com.wind.trademark.common.vo.PageParam;
import com.wind.trademark.task.dao.TaskDao;
import com.wind.trademark.task.model.TkAttachment;
import com.wind.trademark.task.model.TkImg;
import com.wind.trademark.task.model.TkTask;
import com.wind.trademark.task.model.TkTaskCategory;
import com.wind.trademark.task.model.TkTaskContactor;
import com.wind.trademark.task.model.TkTaskLog;
import com.wind.trademark.task.model.TkTaskStatus;
import com.wind.trademark.task.service.TaskService;
import com.wind.trademark.task.vo.AttachmentFileUploadBean;
import com.wind.trademark.task.vo.ImageFileUploadBean;
import com.wind.trademark.task.vo.TaskProfile;
import com.wind.trademark.task.vo.TaskLogVo;




@Service
public class TaskServiceImpl implements TaskService {
	
	@Autowired
	private TaskDao taskDao; 
	@Autowired
	private BaseDao baseDao;
	
	@Value("#{properties['img.repository']}")   
	private String imgRepository;
	@Value("#{properties['file.repository']}")   
	private String fileRepository;
	@Override
	public TkTask saveOrUpateTask(TkTask task) {
	
		task.setCreateBy(1L);
		task.setCreateTime(new Date());
		task.setLastUpdateBy(1L);
		task.setLastUpdateTime(new Date()); 
		CtCompany ctCompany=this.baseDao.get(CtCompany.class, task.getCtCompany().getId());
		task.setCtCompany(ctCompany);
		if(task.getId()==null){
			task.setStatus("APPLY");
			baseDao.save(task);
		}else{
			baseDao.update(task);
		}
		
		List<TkTaskContactor> tkTaskContactorList=this.baseDao.findByProperty(TkTaskContactor.class, "taskId", task.getId());
		for(TkTaskContactor tkTaskContactor:tkTaskContactorList){
			this.baseDao.delete(tkTaskContactor);
		}
		for(TkTaskContactor tkTaskContactor:task.getTkTaskContactores()){
			this.baseDao.save(new TkTaskContactor(null,task.getId(),tkTaskContactor.getContactorId()));
		}
		return task;
	}

	
	@Override
	public void deleteTask(TkTask task) {
		 baseDao.delete(task);
	}
	
	@Override
	public PageBean queryTask(PageParam pageParam, Map<String, Object> params) {
		return taskDao.queryTask(pageParam,params);
	}
	 
	@Override
	public TkTask getTask(Long id) {
		return baseDao.get(TkTask.class, id);
	}

	@Override
	public TkImg getTkImg(Long id) {
		return baseDao.get(TkImg.class, id);
	}

	@Override
	public TkImg saveTkImg(TkImg tkImg) {
		tkImg.setCreateBy(1L);
		tkImg.setCreateTime(new Date());
		tkImg.setLastUpdateBy(1L);
		tkImg.setLastUpdateTime(new Date()); 
		baseDao.save(tkImg);
		return tkImg;
	}
	@Override
	public TkImg saveTkImg(ImageFileUploadBean imageFileUploadBean) throws IOException {
		String path= this.saveImgFromInputStream(imageFileUploadBean);
		
		TkImg tkImg =new TkImg();
		tkImg.setDescription(imageFileUploadBean.getDescription());
		tkImg.setPath(path);
		tkImg.setTaskId(1L);
		tkImg.setCreateBy(1L);
		tkImg.setCreateTime(new Date());
		tkImg.setLastUpdateBy(1L);
		tkImg.setLastUpdateTime(new Date()); 
		baseDao.save(tkImg);
		return tkImg;
	}
	
	@Override
	public TkAttachment saveTkAttachment(
			AttachmentFileUploadBean attachmentFileUploadBean) throws IOException {

		String path= this.saveAttachmentFromInputStream(attachmentFileUploadBean);
		
		TkAttachment tkAttachment =new TkAttachment();
		tkAttachment.setDescription(attachmentFileUploadBean.getDescription());
		tkAttachment.setPath(path);
		tkAttachment.setTaskId(1L);
		tkAttachment.setCreateBy(1L);
		tkAttachment.setCreateTime(new Date());
		tkAttachment.setLastUpdateBy(1L);
		tkAttachment.setLastUpdateTime(new Date()); 
		baseDao.save(tkAttachment);
		return tkAttachment;
	
	}
	
	@Override
	public TkImg updateTkImg(TkImg tkImg) {
		tkImg.setLastUpdateBy(1L);
		tkImg.setLastUpdateTime(new Date()); 
		return tkImg;
	}

	@Override
	public List<TkImg> queryTask(Map<String, Object> params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TkAttachment getTkAttachment(Long id) {
		return this.baseDao.get(TkAttachment.class, id);

	}


	@Override
	public TkAttachment saveTkAttachment(TkImg tkImg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TkAttachment updateTkAttachment(TkImg tkImg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TkAttachment> queryTkAttachment(Map<String, Object> params) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public void addCategoryListToTask(Long taskId,Long categoryId, List<Long> categories) {
		TkTask tkTask=baseDao.get(TkTask.class, taskId);
		tkTask.setBsCategory(this.baseDao.get(BsCategory.class, categoryId));
		baseDao.saveOrUpdate(tkTask);
		taskDao.removeAllCategoryWithTask(taskId);
		for(Long subCategoryId:categories){
			TkTaskCategory tkTaskCategory=new TkTaskCategory();
			tkTaskCategory.setCategoryId(subCategoryId);
			tkTaskCategory.setTaskId(taskId);
			baseDao.save(tkTaskCategory);
		}
	}

	@Override
	public void removeAllCategoryWithTask(Long taskId) {
		taskDao.removeAllCategoryWithTask(taskId);
	}
	
	@Override
	public List<BsCategory> getL3CategoriesByTaskId(Long taskId) {
		return taskDao.getL3CategoriesByTaskId(taskId);
	}
	
	@Override
	public TaskProfile getTask4Bill(Long taskId) {
		return taskDao.getTask4Bill(taskId);
	}
	
	private String saveImgFromInputStream(ImageFileUploadBean imageFileUploadBean) throws IOException {
		MultipartFile file =imageFileUploadBean.getMultipartFile();
		InputStream inputStream = null;
		OutputStream outputStream = null;
		String fileName =null;
		if (!new File(imgRepository).exists()) {
			new File(imgRepository).mkdir();
		}
		
		if (file.getSize() > 0) {
			inputStream = file.getInputStream();
			String root = imgRepository;
			String dir = root+"\\"+imageFileUploadBean.getTaskId();
			if (!new File(dir).exists()) {
				new File(dir).mkdir();
			}
			fileName = dir+"\\"+ file.getOriginalFilename();
			outputStream = new FileOutputStream(fileName);
			int readBytes = 0;
			byte[] buffer = new byte[10000];
			while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {

				outputStream.write(buffer, 0, readBytes);
			}
			outputStream.close();
			inputStream.close();
		}
		return fileName;
	}

	private String saveAttachmentFromInputStream(
			AttachmentFileUploadBean attachmentFileUploadBean) throws IOException {
		MultipartFile file =attachmentFileUploadBean.getMultipartFile();
		InputStream inputStream = null;
		OutputStream outputStream = null;
		String fileName =null;
		if (!new File(imgRepository).exists()) {
			new File(imgRepository).mkdir();
		}
		
		if (file.getSize() > 0) {
			inputStream = file.getInputStream();
			String root = imgRepository;
			String dir = root+"\\"+attachmentFileUploadBean.getTaskId();
			if (!new File(dir).exists()) {
				new File(dir).mkdir();
			}
			fileName = dir+"\\"+ file.getOriginalFilename();
			outputStream = new FileOutputStream(fileName);
			int readBytes = 0;
			byte[] buffer = new byte[10000];
			while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {

				outputStream.write(buffer, 0, readBytes);
			}
			outputStream.close();
			inputStream.close();
		}
		return fileName;
	}
	@Override
	public List<ComboBean> getAllTask() {
		return  taskDao.getAllTask();
	}


	@Override
	public List<TkTask> getAllTask2() {
		return baseDao.findAll(TkTask.class);
	}


	@Override
	public List<ComboBean> goolgeTask(Map<String, Object> params) {
		return taskDao.goolgeTask(params);
	}


	@Override
	public TkTaskLog saveOrUpdateTaskLog(TkTaskLog tkTaskProgress) {
		tkTaskProgress.setCreateBy(1l);
		tkTaskProgress.setCreateTime(new Date());
		tkTaskProgress.setLastUpdateBy(1l);
		tkTaskProgress.setLastUpdateTime(new Date());
		baseDao.saveOrUpdate(tkTaskProgress);
		return tkTaskProgress;
	}


	@Override
	public TkTaskLog loadTaskLog(Long id) {
		return baseDao.get(TkTaskLog.class, id);
	}


	@Override
	public List<TkTaskStatus> getCurrentTaskStatusList(String code) {
		TkTaskStatus tkTaskStatus=baseDao.get(TkTaskStatus.class, code);
		List<TkTaskStatus> result=null;
		if(StringUtils.isNotBlank(tkTaskStatus.getNextSteps())){
			String nextString=tkTaskStatus.getNextSteps();
			List<String> nextSteps=Arrays.asList(nextString.split(","));
			result=taskDao.findNextStepsTaskStatus(nextSteps);
		}else{
			result=new ArrayList<TkTaskStatus>();
		}
		//result.add(0, tkTaskStatus);
		return result;
	}
	@Override
	public List<TkTaskStatus> getTaskStatusList() {
		
		Criteria criteria = baseDao.getHibernateTemplate()
				.getSessionFactory().getCurrentSession()
				.createCriteria(TkTaskStatus.class)
				.add(Example.create(new TkTaskStatus()));
 		criteria.addOrder(Order.asc("sequence"));
 		List<TkTaskStatus> tkTaskStatusList=criteria.list();
 		return tkTaskStatusList;
	}

	@Override
	public TkTask updateTaskStatus(Long taskId,String status) throws TmException {
		TkTask tkTask=this.baseDao.get(TkTask.class, taskId);
		String oldStatus=tkTask.getStatus();
		if(status.equals(oldStatus)){
			String oldStatusName=this.getTaskStatus(oldStatus).getName();
			throw new TmException("该案件的状态已经为["+oldStatusName+"]");
		}else{
			TkTaskLog tkTaskLog=new TkTaskLog();
			tkTaskLog.setTitle("案件状态更新");
			String oldStatusName=this.getTaskStatus(oldStatus).getName();
			String statusName=this.getTaskStatus(status).getName();
			tkTaskLog.setContent(oldStatusName+"-->"+statusName);
			tkTaskLog.setIsSystem("Y");
			tkTaskLog.setTaskId(taskId);
			tkTaskLog.setCreateBy(1L);
			tkTaskLog.setCreateTime(new Date());
			tkTaskLog.setLastUpdateBy(1L);
			tkTaskLog.setLastUpdateTime(new Date());
			this.baseDao.saveOrUpdate(tkTaskLog);

			tkTask.setStatus(status);
			tkTask.setLastUpdateBy(1l);
			tkTask.setLastUpdateTime(new Date());
			this.baseDao.saveOrUpdate(tkTask);
		}

		return tkTask;
	}


	@Override
	public PageBean getLogListByTaskId(PageParam pageParam, Long taskId) {
 		return taskDao.getLogListByTaskId(pageParam,taskId);
	}

	private TkTaskStatus getTaskStatus(String code){
		return this.baseDao.get(TkTaskStatus.class, code);
		
	}


	@Override
	public TkTaskStatus getCurrentStatusByTaskId(Long taskId) {
		return taskDao.getCurrentStatusByTaskId(taskId);
	}


	@Override
	public List<TkImg> getImageListByTaskId(Long taskId) {
		return taskDao.getImageListByTaskId(taskId);
	}
	
	@Override
	public List<TkAttachment> getAttachmentListByTaskId(Long taskId) {
		return taskDao.getAttachmentListByTaskId(taskId);
	}




	@Override
	public void deleteTkImg(List<Long> ids) {
		 this.taskDao.deleteTkImg(ids);		
		
	}


	@Override
	public void deleteTkAttachment(List<Long> ids) {
		 this.taskDao.deleteTkAttachment(ids);		
		
	}






} 